package dao.fileDao;

import dao.interfaces.IPhoto;
import model.Photo;

import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

/**
 * User: Станислав
 * Date: 17.08.14
 */
public class PhotoFileDao implements IPhoto {


    @Override
    public void addPhoto(Photo photo) {
        try {
            FileWriter fileWritter = null;
            List<Photo> photoList = null;
            try {
                photoList = getAllPhoto();
                photoList.add(photo);
                fileWritter = new FileWriter(Path.getPATH(), false);
                Iterator<Photo> iter = photoList.iterator();
                while (iter.hasNext()) {
                    fileWritter.write(iter.next().toString());
                    fileWritter.write("\r\n");
                }

            } finally {
                if (fileWritter != null) {
                    fileWritter.flush();
                    fileWritter.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    @Override
    public void deletePhoto(Photo photo) {
        try {
            FileWriter fileWritter = null;
            List<Photo> photoList = null;
            try {
                photoList = getAllPhoto();
                photoList.remove(photo);
                fileWritter = new FileWriter(Path.getPATH(), false);
                Iterator<Photo> iter = photoList.iterator();
                while (iter.hasNext()) {
                    fileWritter.write(iter.next().toString());
                    fileWritter.write("\r\n");
                }

            } finally {
                if (fileWritter != null) {
                    fileWritter.flush();
                    fileWritter.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    @Override
    public void echo() {
        System.out.println("PhotoFileDao run!");
    }

    @Override
    public List<Photo> getAllPhoto() {
        List<Photo> photoList = new LinkedList<Photo>();
        try {
            FileInputStream fin = null;
            Scanner sc = null;
            try {
                fin = new FileInputStream(Path.getPATH());
                sc = new Scanner(fin);
                Photo tmp = null;
                while (sc.hasNextLine()) {
                    tmp = new Photo(sc.nextLine());
                    photoList.add(tmp);
                }
            } finally {
                if (fin != null) {
                    fin.close();
                }
                if (sc != null) {
                    sc.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return photoList;
    }
}
